import serviceList from "./service";
import request from '@/utils/request';
import {Notification, MessageBox, Message} from 'element-ui'

export default {
  /**
   *
   * @param component 当前组件
   * @param setting action的配置
   * @param params 页面参数
   */
  process(component, setting, params) {
    const requestParams = this.buildQueryParams(component, setting, params);
    let api = null;
    if (setting.serviceType === 'defined') {
      const service = serviceList.find(item => item.code === setting.code);
      api = service.api;
    } else {
      api = this.buildCustomApi(setting, requestParams);
    }
    if (component.showLoading) {
      component.showLoading();
    }
    api(requestParams).then(res => {
      if (res.code === 200) {
        Message.success(res.msg);
      } else {
        Message.error(res.msg);
      }
    }).catch(err => {

    }).finally(()=>{
      if (component.hideLoading) {
        component.hideLoading();
      }
    });
  },

  //构建查询参数
  buildQueryParams(component, setting, params) {
    const queryParams = {};
    if (setting.paramList && setting.paramList.length) {
      setting.paramList.forEach(p => {
        let val;
        if (p.type === '&' && p.value && params[p.value]) { // 动态参数，是进入页面时,url上附带的参数，如 &deviceId=17
          val = params[p.value];

        } else if (p.type === '#' && p.value) {
          // 组件参数，是页面上某个组件的值，作为参数，
          // 如果值是对象，可以用 uuid.prop 的形式获取对象某个属性
          const arr = p.value.split('.');
          const uuid = arr[0];
          // 根据组件uuid找到组件，获取组件的value
          let target = component.$parent.$refs['widget-' + uuid];
          if (target && target.length) {
            target = target[0];
          }
          if (target && target.getValue) {
            val = target.getValue(); // 组件返回的值
            if (arr.length > 1) { // 可以多级查找
              for (let i = 1; i < arr.length; i++) {
                if (val) {
                  val = val[arr[i]];
                }
              }
            }
          }


        } else {
          val = p.value;
        }
        queryParams[p.code] = val;
      })
    }
    return queryParams;
  },

  buildCustomApi(setting, params) {
    let url = setting.url;
    if (url.indexOf('{') !== -1) {
      Object.keys(params).forEach(key => {
        url = url.replace('{' + key + '}', params[key]);
      });
    }
    return function () {
      return request({
        url: url,
        method: setting.requestMethod || 'post',
        params: params,
        data: params
      })
    }
  },
}
